/**
$Id: Caduceus.cpp 3096 2010-07-06 07:21:14Z Bear $

Copyright (c) 2010 Nuwa Information Co., Ltd, and individual contributors.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.

  3. Neither the name of Nuwa Information nor the names of its contributors
     may be used to endorse or promote products derived from this software
     without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

$Author: Bear $
$Date: 2010-07-06 15:21:14 +0800 (星期二, 06 七月 2010) $
$Revision: 3096 $
*/

#ifdef _PYTHON

#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/python.hpp>

#include <pion/PionPlugin.hpp>
#include <pion/net/WebServer.hpp>
//#include <ShutdownManager.hpp>

#include "Caduceus.hpp"
#include "../WsgiService.hpp"
#include "../wsgi-int.h"

// These are used only when linking to static web service libraries.
// #ifdef PION_STATIC_LINKING
PION_DECLARE_PLUGIN(FileService)
PION_DECLARE_PLUGIN(CookieService)
PION_DECLARE_PLUGIN(WsgiService)

WsgiWebServer::WsgiWebServer(const boost::asio::ip::tcp::endpoint& endpoint,
                             const std::string& resource, 
                             boost::python::object& handler)
 : cleaned(false), pion::net::WebServer(endpoint)
{
 init(endpoint, resource, handler);
}

WsgiWebServer::WsgiWebServer(PionSchedulerPtr& _scheduler,
                             const boost::asio::ip::tcp::endpoint& endpoint,
                             const std::string& resource, 
                             boost::python::object& handler)
 : scheduler(_scheduler), cleaned(false), pion::net::WebServer(*_scheduler, endpoint)
{
 init(endpoint, resource, handler);
}

bool WsgiWebServer::init(const boost::asio::ip::tcp::endpoint& endpoint,
                         const std::string& resource, 
                         boost::python::object& handler)
{
 // We load WsgiService automatically to resource.
 // Service will be deleted after PluginManager after server destructed.
 pion::plugins::WsgiService* srv = new pion::plugins::WsgiService;
 // Set up port.
 srv->setOption("port", boost::lexical_cast<std::string>(endpoint.port()));

 // Set up WSGIHandler.
 this->handler = handler;
 // Add service.
 addService(resource, srv);

 return true;
}

WsgiWebServer::~WsgiWebServer()
{
 if(!cleaned)
 {
  wsgiCleanup2();
  cleaned = true;
 }
}

void WsgiWebServer::start()
{
 pion::net::WebServer::start();
}

void WsgiWebServer::stop()
{
 // Directly call stop, wsgiCleanup will be called by warp function.
 cleaned = true;
 pion::net::WebServer::stop();
}

void WsgiWebServer::loadService(const std::string& resource, 
                                const std::string& service)
{
 // We ignore loaded resource or service instead of throwing exception.
 try
 {
  pion::net::WebServer::loadService(resource, service);
 }
 catch(pion::PluginManager<pion::net::WebService>::DuplicatePluginException)
 {
  return;
 }
}

WsgiWebServerPtr CreateWebServer(boost::python::object& handler,
                                 const std::string& resource,
                                 const boost::uint32_t port, 
                                 //PionSchedulerFactoryPtr scheduler,
                                 const std::string& ip,
                                 bool log)
{
 // Initialize log system (use simple configuration).
 pion::PionLogger logger(PION_GET_LOGGER("WsgiWebServer"));
 if(log)
 {
#ifdef _DEBUG
  PION_LOG_SETLEVEL_DEBUG(logger);
#else
  PION_LOG_SETLEVEL_INFO(logger);
#endif
  PION_LOG_CONFIG_BASIC;
 }

 boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), 8080);
 endpoint.port(port);

 if(!ip.empty())
  endpoint.address(boost::asio::ip::address::from_string(ip));

 // Create a server.
 try
 {
  // FIXME: Nerver called until we find a way to use other schedulers.
  /*
  if(scheduler) 
  {
   return WsgiWebServerPtr(new WsgiWebServer(scheduler->Create(), endpoint, 
                                             resource, handler));
  }
  else
  */
  {
   return WsgiWebServerPtr(new WsgiWebServer(endpoint, resource, handler));
  }
 }
 catch(std::exception& e) 
 {
  PION_LOG_FATAL(logger, e.what());
  throw e;
 }
}

PionSchedulerFactoryPtr CreatePionSingleServiceSchedulerFactory(
 const boost::uint32_t threads)
{
 PionSingleServiceSchedulerFactoryPtr p(
  new PionSingleServiceSchedulerFactory(threads));
 return boost::dynamic_pointer_cast<PionSchedulerFactory>(p);
}

PionSchedulerFactoryPtr CreatePionOneToOneSchedulerFactory(
 const boost::uint32_t threads)
{
 PionOneToOneSchedulerFactoryPtr p(
  new PionOneToOneSchedulerFactory(threads));
 return boost::dynamic_pointer_cast<PionSchedulerFactory>(p);
}

#ifdef WIN32
#include <windows.h>

/**
Win32 DLL Entry pointer.
*/
BOOL APIENTRY DllMain(HANDLE hModule, 
                      DWORD fdwReason, 
                      LPVOID lpReserved)
{
 switch (fdwReason)
 {
  case DLL_PROCESS_ATTACH:
   break;

  case DLL_PROCESS_DETACH:
#ifdef DEBUG
   _CrtDumpMemoryLeaks();
#endif
   break;

  default:
   break;
 }

 return TRUE;
}

#else
#endif

#endif
